package damon.utils;

import java.util.Arrays;

public class DataToBytes {
    static public byte[] stringToBytes(String s ){
        return s.getBytes();
    }

    static public byte[] shortToBytes(short s ){
        byte[] bytes = new byte[2];
        bytes[0] = (byte) ((s & 0xff00) >> 8);
        bytes[1] = (byte) (s & 0x00ff);
        return bytes;
    }

    static public byte[] intToBytes(int i ){
        byte[] bytes = new byte[4];
        bytes[0] = (byte) ((i & 0xff000000) >> 24);
        bytes[1] = (byte) ((i & 0x00ff0000) >> 16);
        bytes[2] = (byte) ((i & 0x0000ff00) >> 8);
        bytes[3] = (byte)  (i & 0x000000ff);
        return bytes;
    }

    static public byte[] longToBytes(long l ){
        byte bytes[] = new byte[8];
        bytes[0] = (byte)  (0xff & (l >> 56));
        bytes[1] = (byte)  (0xff & (l >> 48));
        bytes[2] = (byte)  (0xff & (l >> 40));
        bytes[3] = (byte)  (0xff & (l >> 32));
        bytes[4] = (byte)  (0xff & (l >> 24));
        bytes[5] = (byte)  (0xff & (l >> 16));
        bytes[6] = (byte)  (0xff & (l >> 8));
        bytes[7] = (byte)  (0xff & l);
        return bytes;
    }

    static public byte[] floatToBytes(float f ){
        int floatToIntBits = Float.floatToIntBits(f);//将float里面的二进制串解释为int整数
        return intToBytes(floatToIntBits);
    }

    static public byte[] doubleToBytes(double d ){
        long doubleToLongBits = Double.doubleToLongBits(d);
        return longToBytes(doubleToLongBits);

    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(stringToBytes("777")));
        System.out.println(Arrays.toString(shortToBytes((short) 4)));
        System.out.println(Arrays.toString(intToBytes(88)));
        System.out.println(Arrays.toString(longToBytes(8876l)));
        System.out.println(Arrays.toString(floatToBytes(7777.987f)));
        System.out.println(Arrays.toString(doubleToBytes(7865.78543)));
//        System.out.println(Arrays.toString());
//        System.out.println(Arrays.toString());
    }
}
